# Based on the sed script posted at
# http://davidgolightly.blogspot.com/2007/07/one-line-css-minifier.html
#
class CssMin
  def self.mime_type
    "text/css"
  end

  def self.minify(css)
    css = css.
      gsub(%r!^[ \t]*!m, '').           # remove leading space
      gsub(%r![ \t]*$!m, '').           # remove trailing space
      gsub(%r!\s*([:;{},])\s*!m, '\1'). # remove spaces before/after a colon, braces, semicolon, or comma
      gsub(%r!\(\s*!, '(').             # remove spaces after a start paren
      gsub(%r!\s*\)!, ')').             # remove spaces before an end paren
      gsub(%r!/\*.*?\*/!m, '').         # remove comments
      gsub(%r![\r\n]+!, '')             # remove all newlines

    # 0px -> 0
    css.gsub!(%r!([\s:])0(px|em|%|in|cm|mm|pc|pt|ex)!, '\10')

    # compress #aabbcc -> #abc
    css = css.gsub(%r!#[0-9a-fA-F]{6}!) do |color|
      firsts = color.split('').values_at(1,3,6)
      color.downcase == "##{firsts.map { |c| c * 2 }.join}".downcase ?
        "##{firsts.join}" :
        color
    end
  end
end
